package com.mobi.Survey.lib.uicomponents;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.mobi.Survey.lib.activities.AbstractScreen;
import com.mobi.Survey.lib.activities.Messages;
import com.mobi.Survey.lib.exceptions.EmptyFieldException;
import com.mobi.Survey.lib.model.SurveyDetailPojo;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * ControlFactory.java This class is responsible for creating of new controls
 * and retrieving user's input from controls Table
 * 
 */
public class ControlFactory {
	public static final byte CONTROL_TYPE_ZERO = 0;
	public static final byte CONTROL_EDIT_TEXT = 1;
	public static final byte CONTROL_RADIOGROUP = 2;
	public static final byte CONTROL_RATINGBAR = 3;
	public static final byte CONTROL_SPINNER = 4;
	public static final byte CONTROL_CHECK_BOX = 5;
	public static final byte CONTROL_IMAGE_VIEW = 6;
	public static final byte CONTROL_VIDEO_VIEW = 7;
	public static final byte CONTROL_TIME = 8;
	public static final byte CONTROL_DATE = 9;
	public static final byte CONTROL_URL = 10;
	public static final byte CONTROL_EMAIL = 14;
	public static final byte CONTROL_ADDRESS = 16;
	public static final byte CONTROL_PHONE = 15;
	public static final byte CONTROL_TIMER = 17;

	public static final String ERROR_CONTROL_EDIT_TEXT = Messages.EDIT_TEXT_ERROR;
	public static final String ERROR_CONTROL_RADIOGROUP = Messages.RADIO_GROUP_ERROR;
	public static final String ERROR_CONTROL_RATINGBAR = Messages.RATINGBAR_ERROR;
	public static final String ERROR_CONTROL_SPINNER = Messages.DROP_DOWN_ERROR;
	public static final String ERROR_CONTROL_CHECK_BOX = Messages.CHECK_BOX_ERROR;

	
	
	public static final boolean isInputControl(final SurveyDetailPojo sdp) {
		boolean is = false;

		byte compType = sdp.getControlType();
		switch (compType) {

		case CONTROL_EDIT_TEXT:
		case CONTROL_RADIOGROUP:
		case CONTROL_RATINGBAR:
		case CONTROL_SPINNER:
		case CONTROL_CHECK_BOX:
		case CONTROL_DATE:
		case CONTROL_TIME:
			is = true;

		}

		return is;
	}
	
	
	/**
	 * For retrieving User input we will pass control text to the getUserinput
	 * method of particular control to get proper index of control inside Layout
	 * if control text is not null the index of control in layout will be
	 * greater than 0
	 * 
	 * @param sdps
	 *            Collection of SurveyDetailPojos
	 * @param views
	 *            Collection of Control Views
	 * @throws RuntimeException
	 *             if some exception throws or user does't provide input for
	 *             Mandatory control
	 */
	public static void getUserInputs(List<SurveyDetailPojo> sdps,
			List<View> views) throws RuntimeException {
		int index = 0;

		for (SurveyDetailPojo sp : sdps) {

			View v = views.get(index);

			String ctr_text = sp.getControlText();
			switch (sp.getControlType()) {

			case CONTROL_EDIT_TEXT:

				String editResult = forEditTextResult(ctr_text, sp, v);
				if (sp.isMendatory() && editResult.equals("")) {
					throw new EmptyFieldException(ERROR_CONTROL_EDIT_TEXT,
							index);
				}
				sp.setUsertValue(editResult);

				break;

			case CONTROL_RADIOGROUP:

				String radGroup = forRadioGroupResult(ctr_text, sp, v);
				if (sp.isMendatory() && radGroup.equals(""))
					throw new EmptyFieldException(ERROR_CONTROL_RADIOGROUP,
							index);

				sp.setUsertValue(radGroup);
				break;

			case CONTROL_RATINGBAR:
				float ratingResult = forRatingBarResult(ctr_text, sp, v);

				if (sp.isMendatory() && ratingResult == 0.0)
					throw new EmptyFieldException(ERROR_CONTROL_RATINGBAR,
							index);

				sp.setUsertValue(ratingResult + "");
				break;

			case CONTROL_SPINNER:

				String spinnerResult = forSpinnerResult(ctr_text, sp, v);
				// if (sp.isMendatory() && spinnerResult.equals("abc"));
				// throw new RuntimeException(ERROR_CONTROL_SPINNER);
				sp.setUsertValue(spinnerResult);
				break;

			case CONTROL_CHECK_BOX:
				String selectedCB = forCheckBoxResult(ctr_text, sp, v);

				if (sp.isMendatory() && selectedCB.length() == 0)
					throw new EmptyFieldException(ERROR_CONTROL_CHECK_BOX,
							index);
				sp.setUsertValue(selectedCB + "");
				break;

			case CONTROL_IMAGE_VIEW:

				break;
			case CONTROL_VIDEO_VIEW:

				break;

			case CONTROL_DATE:
				String date = forDatePickerResult(ctr_text, sp, v);
				sp.setUsertValue(date + "");
				break;
			case CONTROL_TIME:
				String time = forTimePickerResult(ctr_text, sp, v);
				sp.setUsertValue(time + "");
				break;

			}

			index++;
		}

	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param view
	 * @return
	 */
	private static String forTimePickerResult(String ctr_text,
			SurveyDetailPojo sp, View view) {
		LinearLayout ll = (LinearLayout) view;
		int index = 0;
		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}

		CustomTimePicker ctp = (CustomTimePicker) ll.getChildAt(index);
		String hours = ctp.getCurrentHour().toString();
		String mins = ctp.getCurrentMinute().toString();
		return hours + CustomTimePicker.DELIM + mins;

	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param view
	 * @return value of control
	 */

	private static String forDatePickerResult(String ctr_text,
			SurveyDetailPojo sp, View view) {
		int index = 0;
		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}
		String month = "";
		String yr = "";
		String day = "";
		LinearLayout ll = (LinearLayout) view;
		CustomDatePicker cdp = (CustomDatePicker) ll.getChildAt(index);
		month = CustomDatePicker
				.getMonthNameByNumber((byte) (cdp.getMonth() + 1));
		yr = String.valueOf(cdp.getYear());
		day = String.valueOf(cdp.getDayOfMonth());

		return month + CustomDatePicker.DELIM + day + CustomDatePicker.DELIM
				+ yr;

	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param v
	 * @return value of control
	 */
	private static String forCheckBoxResult(String ctr_text,
			SurveyDetailPojo sp, View v) {
		LinearLayout ll = (LinearLayout) v;
		String selection = "";
		int index = 0;
		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}
		int totalChild = ll.getChildCount();

		for (int i = index; i < totalChild; i++) {
			CustomCheckedBox cb = (CustomCheckedBox) ll.getChildAt(i);
			if (cb.isChecked()) {
				selection += cb.getText().toString() + CustomCheckedBox.DELIM;
			}

		}
		String result = "";
		if (selection.endsWith(CustomCheckedBox.DELIM)) {
			result = selection.substring(0, selection.length() - 1);

		}

		return result;

	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param v
	 *            selected value
	 * @return
	 */
	private static String forSpinnerResult(String ctr_text,
			SurveyDetailPojo sp, View v) {

		LinearLayout ll = (LinearLayout) v;
		int index = 0;
		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}

		CustomSpinner spinner = (CustomSpinner) ll.getChildAt(index);
		String item = spinner.getSelectedItem().toString();
		return item;
	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param v
	 * @return selected value
	 */
	private static float forRatingBarResult(String ctr_text,
			SurveyDetailPojo sp, View v) {
		LinearLayout ll = (LinearLayout) v;
		int index = 0;
		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}

		CustomRatingBar rating = (CustomRatingBar) ll.getChildAt(index);
		return rating.getRating();

	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param v
	 * @return selected value
	 */
	private static String forRadioGroupResult(String ctr_text,
			SurveyDetailPojo sp, View v) {
		LinearLayout ll = (LinearLayout) v;
		int index = 0;
		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}
		CustomRadioGroup rbgrp = (CustomRadioGroup) ll.getChildAt(index);
		int id = rbgrp.getCheckedRadioButtonId();
		if (id > -1) {
			CustomRadioButton rb = (CustomRadioButton) rbgrp.findViewById(id);
			if (rb.isChecked()) {
				return rb.getText().toString();
			}
		}
		return "";

	}

	/**
	 * 
	 * @param ctr_text
	 * @param sp
	 * @param v
	 * @return selected value
	 */
	private static String forEditTextResult(String ctr_text,
			SurveyDetailPojo sp, View v) {
		String result = null;
		LinearLayout ll = (LinearLayout) v;
		int index = 0;

		if (ctr_text != null && ctr_text.length() > 0) {
			index++;
		}
		CustomEditText edit = (CustomEditText) ll.getChildAt(index);

		result = edit.getText().toString();
		if (result == null)
			result = "";
		return result.trim();

	}

	/**
	 * 
	 * @param sdp
	 *            Provide Survey detail pojo and creates a view on base of user
	 *            input data
	 * @param ctx
	 * @param clickEnable
	 *            if user can interact with control or not. Right now this value
	 *            will not effect because user can not interact with control for
	 *            answer screen
	 * @return returns Control
	 */
	public static View createControlForAnswerScreen(SurveyDetailPojo sdp,
			Context ctx, boolean clickEnable) {

		byte compType = sdp.getControlType();
		View v = null;
		CustomTextView ctvCorrectAnswer = new CustomTextView(ctx);
		// Type of component for which create View
		switch (compType) {

		case CONTROL_EDIT_TEXT:
			CustomEditText edit = new CustomEditText(ctx, sdp, false);
			v = edit.getView();

			sdp.getActualValue().replace(CustomCheckedBox.DELIM, "\n");
			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ "\n"
					+ sdp.getActualValue()
							.replace(CustomCheckedBox.DELIM, "\n"));
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			v.setPadding(0, 0, 0, 30);
			((ViewGroup) v).addView(ctvCorrectAnswer);
			break;

		case CONTROL_RADIOGROUP:
			CustomRadioGroup crg = new CustomRadioGroup(ctx, sdp, false);
			v = crg.getView();

			sdp.getActualValue().replace(CustomCheckedBox.DELIM, "\n");
			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ "\n"
					+ sdp.getActualValue()
							.replace(CustomCheckedBox.DELIM, "\n"));
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			v.setPadding(0, 0, 0, 30);
			((ViewGroup) v).addView(ctvCorrectAnswer);
			break;

		case CONTROL_RATINGBAR:
			CustomRatingBar crb = new CustomRatingBar(ctx, sdp, false);
			// crb.setRating(Helper.toFloat(sdp.getu));
			v = crb.getView();

			sdp.getActualValue().replace(CustomCheckedBox.DELIM, "\n");
			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ "\n"
					+ sdp.getActualValue()
							.replace(CustomCheckedBox.DELIM, "\n"));
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			v.setPadding(0, 0, 0, 30);
			((ViewGroup) v).addView(ctvCorrectAnswer);
			break;

		case CONTROL_SPINNER:
			CustomSpinner cspr = new CustomSpinner(ctx, sdp, false);
			v = cspr.getView();

			sdp.getActualValue().replace(CustomCheckedBox.DELIM, "\n");
			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ "\n"
					+ sdp.getActualValue()
							.replace(CustomCheckedBox.DELIM, "\n"));
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			v.setPadding(0, 0, 0, 30);
			((ViewGroup) v).addView(ctvCorrectAnswer);
			break;

		case CONTROL_CHECK_BOX:
			CustomCheckedBox cctxtview = new CustomCheckedBox(ctx, sdp, false);
			v = cctxtview.getView();

			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ "\n"
					+ sdp.getActualValue()
							.replace(CustomCheckedBox.DELIM, "\n"));
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			v.setPadding(0, 0, 0, 30);
			((ViewGroup) v).addView(ctvCorrectAnswer);
			return v;

		case CONTROL_DATE:
			CustomDatePicker cdp = new CustomDatePicker(ctx, sdp, false);

			v = cdp.getView();

			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ sdp.getActualValue().replace(CustomTextView.DELIM, "-"));

			// ((ViewGroup) v).addView(ctvYourAnswer);
			((ViewGroup) v).addView(ctvCorrectAnswer);
			v.setPadding(0, 0, 0, 30);
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			return v;

		case CONTROL_TIME:
			CustomTimePicker ctp = new CustomTimePicker(ctx, sdp, false);
			v = ctp.getView();

			ctvCorrectAnswer.setText(Messages.CORRECT_ANSWER
					+ sdp.getActualValue().replace(CustomTextView.DELIM, "-"));

			((ViewGroup) v).addView(ctvCorrectAnswer);
			v.setPadding(0, 0, 0, 30);
			ctvCorrectAnswer.setTextColor(Color.GREEN);
			return v;

		}

		return v;
	}

	/**
	 * 
	 * @param sdp
	 *            SurveyDetailPojo
	 * @param ctx
	 * @param showAllControls
	 *            If Single Screen Instead of ImageView/VideoView interactive
	 *            buttons will be created for surveyDetail
	 * @return return view on base of given SurveyDetailPojo
	 */
	

	public static View createControl(final SurveyDetailPojo sdp,
			final Context ctx, boolean showAllControls) {

		byte compType = sdp.getControlType();
		View v = null;
		CustomTextView customTv = null;
		String txtCtrl = null;
		LinearLayout ll = null;

		switch (compType) {

		case CONTROL_EDIT_TEXT:
			CustomEditText edit = new CustomEditText(ctx, sdp, true);
			v = edit.getView();
			break;

		case CONTROL_RADIOGROUP:// Ok Color
			CustomRadioGroup crg = new CustomRadioGroup(ctx, sdp, true);

			v = crg.getView();
			break;

		case CONTROL_RATINGBAR:
			CustomRatingBar crb = new CustomRatingBar(ctx, sdp, true);
			// crb.setRating(Helper.toFloat(sdp.getu));
			v = crb.getView();
			break;

		case CONTROL_SPINNER: // Ok Color
			CustomSpinner cspr = new CustomSpinner(ctx, sdp, true);
			v = cspr.getView();
			break;

		case CONTROL_CHECK_BOX: // Ok Color
			CustomCheckedBox cctxtview = new CustomCheckedBox(ctx, sdp, true);

			v = cctxtview.getView();
			break;

		case CONTROL_IMAGE_VIEW:

		{
			CustomImageView img = new CustomImageView(ctx, sdp);
			v = img.getView();
		}
			break;
		case CONTROL_VIDEO_VIEW:
			if (showAllControls) {

				Button btnIv = new Button(ctx);

				btnIv.setText(Messages.VIDEO_BUTTON);

				ll = new LinearLayout(ctx);

				ll.setOrientation(LinearLayout.VERTICAL);

				if (sdp.getControlText() != null
						&& sdp.getControlText().length() > 0) {
					CustomTextView txt = new CustomTextView(ctx);
					txt.setCustomColor(sdp);
					txt.setText(sdp.getControlText());
					ll.addView(txt);

				}
				ll.addView(btnIv);
				v = ll;
			} else {

				CustomImageView img = new CustomImageView(ctx, sdp);
				v = img.getView();

			}
			break;
		case CONTROL_DATE: // Ok Color
			CustomDatePicker cdp = new CustomDatePicker(ctx, sdp, true);
			cdp.applyFontRecursively(cdp, sdp);
			v = cdp.getView();
			break;

		case CONTROL_TIME:// Ok Color
			CustomTimePicker ctp = new CustomTimePicker(ctx, sdp, true);

			ctp.applyFontRecursively(ctp, sdp);
			v = ctp.getView();
			break;

		case CONTROL_URL:

			txtCtrl = sdp.getControlText();
			if (txtCtrl == null || txtCtrl.length() == 0) {
				txtCtrl = Messages.CTRL_TXT_WEBSITE;

			}
//			sdp.setControlText("");
			ll = new LinearLayout(ctx);
			ll.setOrientation(LinearLayout.VERTICAL);

			String ctrlParam = sdp.getControlParameter1();

			customTv = new CustomTextView(ctx);
			customTv.setText(txtCtrl);
			customTv.setCustomColor(sdp);
			ll.addView(customTv);

			customTv = new CustomTextView(ctx);
			customTv.setText(Html.fromHtml("<a href = \"" + ctrlParam + "\">"
					+ ctrlParam + "</a>"));
			ll.addView(customTv);

			customTv.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					((AbstractScreen) ctx).openUrl(sdp.getControlParameter1());

				}
			});

			v = ll;
			break;

		case CONTROL_EMAIL:

			txtCtrl = sdp.getControlText();
			if (txtCtrl == null || txtCtrl.length() == 0) {
				txtCtrl = Messages.CTRL_TXT_EMAIL;

			}
//			sdp.setControlText("");
			ll = new LinearLayout(ctx);
			ll.setOrientation(LinearLayout.VERTICAL);

			ctrlParam = sdp.getControlParameter1();

			customTv = new CustomTextView(ctx);
			customTv.setText(txtCtrl);
			customTv.setCustomColor(sdp);
			ll.addView(customTv);

			customTv = new CustomTextView(ctx);
			customTv.setText(Html.fromHtml("<a href = \"" + ctrlParam + "\">"
					+ ctrlParam + "</a>"));
			ll.addView(customTv);

			customTv.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					((AbstractScreen) ctx).sendEmail(sdp.getControlParameter1(),
							"Need more information",
							"Please provide me more information about below features. ");

				}
			});

			v = ll;

			break;
		case CONTROL_ADDRESS:

			txtCtrl = sdp.getControlText();
			if (txtCtrl == null || txtCtrl.length() == 0) {
				txtCtrl = Messages.CTRL_TXT_ADDRESS;

			}
		//	sdp.setControlText("");
			ll = new LinearLayout(ctx);
			ll.setOrientation(LinearLayout.VERTICAL);

			ctrlParam = sdp.getActualValue();

			customTv = new CustomTextView(ctx);
			customTv.setText(txtCtrl);
			customTv.setCustomColor(sdp);
			ll.addView(customTv);

			customTv = new CustomTextView(ctx);
			customTv.setText(Html.fromHtml("<a href = \"" + ctrlParam + "\">"
					+ ctrlParam + "</a>"));
			ll.addView(customTv);

			customTv.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					((AbstractScreen) ctx).openMapByAddress(sdp
							.getActualValue());

				}
			});

			v = ll;

			break;
		case CONTROL_PHONE:
			if (((AbstractScreen) ctx).canCall()) {

				txtCtrl = sdp.getControlText();
				if (txtCtrl == null || txtCtrl.length() == 0) {
					txtCtrl = Messages.CTRL_TXT_PHONE;

				}
				// sdp.setControlText("");
				ll = new LinearLayout(ctx);
				ll.setOrientation(LinearLayout.VERTICAL);

				ctrlParam = sdp.getControlParameter1();

				customTv = new CustomTextView(ctx);
				customTv.setText(txtCtrl);
				customTv.setCustomColor(sdp);
				ll.addView(customTv);
				customTv = new CustomTextView(ctx);
				customTv.setText(Html.fromHtml("<a href = \"" + ctrlParam
						+ "\">" + ctrlParam + "</a>"));
				ll.addView(customTv);

				customTv.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						((AbstractScreen) ctx).makeCall(sdp
								.getControlParameter1());

					}
				});

				v = ll;
			}

			break;

		// If control type does't match create a TextView
		default:
			CustomTextView ctv = new CustomTextView(ctx, null);
			ctv.setCustomColor(sdp);
			String txtCtr = sdp.getControlText();
			String txtParam = sdp.getControlParameter1();
			if (txtCtr == null || txtCtr.length() == 0)
				txtCtr = Messages.NO_CONTROL_TEXT;

			ctv.setText(txtCtr);

			v = ctv.getView();

			if (txtParam != null && txtParam.length() > 0) {
				((LinearLayout) v).setOrientation(LinearLayout.VERTICAL);
				ctv = new CustomTextView(ctx);
				ctv.setCustomColor(sdp);
				ctv.setText(txtParam);
				((LinearLayout) v).addView(ctv);

			}

			break;

		}// Padding
		v.setPadding(0, 0, 0, 20);
		return v;
	}

	 
}
